﻿using Knight.Interface;
using Knight.Models.Entity;
using Knight.Models.Services;
using Knlght.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WebApp.Areas.Manage.Controllers.Filters
{
    public class PermissionAttribute : FilterAttribute, IResultFilter
    {
        readonly string _menuId = "";
        public PermissionAttribute()
        { }
        public PermissionAttribute(string menuId)
        {
            this._menuId = menuId;
        }

        public void OnResultExecuted(ResultExecutedContext filterContext)
        {

        }

        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (filterContext.Result is ViewResult)
            {
                var service = Knight.ObjectFactory.ObjectFactory.Get<IDefaultService>();
                var response = service.GetModel<Administrators>(filterContext.HttpContext.User.Identity.Name);
                if (response.IsSuccess && response.Model != null)
                {
                    if (!response.Model.IsSuper)
                    {
                        var query = new QueryRequest<RoleInfo>();
                        query.Add(o => o.Id == response.Model.OwmRoleId);
                        var rep = service.GetModel<RoleInfo>(query.SubQueries);
                        if (rep.IsSuccess && rep.Model != null)
                        {
                            if (!rep.Model.Jurisdiction.Split(',').Contains(this._menuId))
                            {
                                filterContext.HttpContext.Response.Write("<script>alert('没权限访问');location.href='/Home/Index'</script>");
                            }
                        }
                        else
                        {
                            filterContext.HttpContext.Response.Write("<script>alert('没权限访问');location.href='/Home/Index'</script>");
                        }
                    }
                }
                else
                {
                    //取消Session会话
                    filterContext.HttpContext.Session.Abandon();
                    //删除Forms验证票证
                    FormsAuthentication.SignOut();
                    filterContext.HttpContext.Response.Write("<script>alert('操作超时，请重新登录');location.href='/Account/Login'</script>");
                }
            }
        }
    }
}